package com.csnf.servlet;

import com.csnf.entity.Student;
import com.csnf.service.StudentService;
import com.csnf.service.impl.StudentServicelmpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.time.LocalDate;

@WebServlet(name = "StudentServlet", value = {"/StudentServlet","/getAllStudent","/deleteStudent"})
public class StudentServlet extends HttpServlet {
    StudentService studentService  = new StudentServicelmpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        getStu(req, resp);
    }

    private void getStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("studentList",studentService.gatAll());
        req.getRequestDispatcher("stdent.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //获取页面填写信息
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        String sBirthday = req.getParameter("birthday");
        LocalDate birthday = LocalDate.parse(sBirthday);
        String clazz = req.getParameter("clazz");
        String state = req.getParameter("state");
        //通过信息创建学生对象
        Student student = new Student(null,name,gender,birthday,clazz,state);
        Boolean flag =false;
        try {
           studentService.addStudent(student);  //调用保存方法
        } catch (Exception e) {
            e.printStackTrace();
        }

        getStu(req, resp);
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();
        if ("/deleteStudent".equals(servletPath)){
            deleteStu(req,resp);
        }
    }
    private void deleteStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        studentService.deleteById(Integer.parseInt(id));
        getStu(req, resp);
    }
}
